<script setup lang="ts">
import { StudentApi } from '@/apis'
import type { TableInstanceColumns } from '@/components/ProTable/type'
import StudentStatus from '@/views/education/student/components/StudentStatus.vue'
import { useDictLabel, useTable } from '@/hooks'
import getAvatar from '@/utils/avatar'

const emit = defineEmits(['select'])

const visible = ref(false)
const selectedKeys = ref<string[]>([])

const queryForm = reactive<StudentApi.StudentQuery>({
  keyword: undefined,
  // sort: ['createTime,desc'],
})

const {
  tableData: dataList,
  loading,
  pagination,
  search,
} = useTable(page => StudentApi.getStudentPage({ ...queryForm, ...page }), { immediate: false })

const columns: TableInstanceColumns[] = [
  {
    title: '姓名',
    slotName: 'name',
    width: 120,
  },
  { title: '联系方式', dataIndex: 'parentPhone', slotName: 'parentPhone', width: 220 },
  // { title: '招生来源', dataIndex: 'source', ellipsis: true, tooltip: true, render: ({ record }) => useDictLabel('StudentSource', record.source) },
]

const rowSelection = {
  type: 'radio',
  showCheckedAll: false,
  onlyCurrent: false,
}

const open = () => {
  visible.value = true
  selectedKeys.value = []
  search()
}

const onConfirm = async () => {
  if (selectedKeys.value.length > 0) {
    emit('select', selectedKeys.value[0])
  }
}

const onRowClick = (row) => {
  selectedKeys.value = [row.id]
}

defineExpose({ open })
</script>

<template>
  <a-modal
    v-model:visible="visible"
    title="选择学生"
    width="560px"
    :ok-button-props="{ disabled: selectedKeys.length === 0 }"
    @before-ok="onConfirm"
  >
    <a-spin :loading="loading" tip="数据获取中..." style="width: 100%; height: 100%;">
      <ProTable
        v-model:selectedKeys="selectedKeys"
        :data="dataList"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        :disabled-tools="['size', 'setting']"
        :disabled-column-keys="['name']"
        @refresh="search"
        @row-click="onRowClick"
      >
        <template #toolbar-left>
          <a-input-search v-model="queryForm.keyword" placeholder="根据姓名/拼音/手机号查询" allow-clear style="width: 300px" @search="search" @press-enter="search" />
        </template>
        <template #name="{ record }">
          <CellAvatar :avatar="getAvatar(record.avatar, record.gender)" :name="record.name" :is-link="false" />
        </template>
        <template #gender="{ record }">
          <CellGender :gender="record.gender" />
        </template>
        <template #status="{ record }">
          <StudentStatus :status="record.status" />
        </template>
        <template #parentPhone="{ record }">
          <CellParentInfo :phone="record.parentPhone" :relation="record.parentRelation" />
        </template>
      </ProTable>
    </a-spin>
  </a-modal>
</template>

<style lang="less" scoped>

</style>
